package BM.test;

import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.IBinder;
import android.widget.RemoteViews;
//import android.widget.Toast;

public class BatteryManagementService extends Service {

	@Override
	public void onDestroy() {
		unregisterReceiver(bCR);
		super.onDestroy();
	}

	private BroadcastReceiver bCR = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			int level = intent.getIntExtra("level", 0);
			int scale = intent.getIntExtra("scale", 100);
			int status = intent.getIntExtra("status", 0);
			int batteryHealth = level * 100 / scale;
//			int plugged = intent.getIntExtra("plugged", 0);
			AppWidgetManager widgetManager = AppWidgetManager
					.getInstance(context);
			RemoteViews widgetView = new RemoteViews(context.getPackageName(),
					R.layout.appwidget);
			widgetView.setTextViewText(R.id.widgetTextId, batteryHealth
					+ "%");
			widgetView.setImageViewResource(R.id.imageId,
					getIcon(status, batteryHealth));
			widgetManager.updateAppWidget(new ComponentName(context,
					BatteryAppWidgetProvider.class), widgetView);
			Intent batteryIntent=new Intent();
			batteryIntent.setAction(BatteryAppWidgetProvider.UPDATE_Battery_ACTION);
			batteryIntent.putExtras(intent.getExtras());
			context.sendBroadcast(batteryIntent);
		}
	};

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		registerReceiver(this.bCR, new IntentFilter(
				Intent.ACTION_BATTERY_CHANGED));
		// return super.onStartCommand(intent, flags, startId);
		return START_NOT_STICKY;
	}

	private int getIcon(int status, int batteryHealth) {
		return batteryStateIcon[batteryHealth / 11
				+ ((status != BatteryManager.BATTERY_STATUS_NOT_CHARGING) ? 0 : 10)];
	}

	 private int batteryStateIcon[] = { 0x7f020000, 0x7f020001, 0x7f020002,
	 0x7f020003, 0x7f020004, 0x7f020005, 0x7f020006, 0x7f020007,
	 0x7f020008, 0x7f020009, 0x7f02000c, 0x7f02000d,
	 0x7f02000e, 0x7f02000f, 0x7f020010, 0x7f020011, 0x7f020012,
	 0x7f020013, 0x7f020014,0x7f020015 };
}
